package com.idanchuang.component.businesslog.es.index;

import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * The IndexManagerPolicy
 *
 * @since 2020/7/17
 */
public class IndexManagerPolicy implements ToXContentObject {

    static final ParseField DESCRIPTION_FIELD = new ParseField("description");
    static final ParseField DEFAULT_STATE = new ParseField("default_state");
    static final ParseField STATES_FIELD = new ParseField("states");

    private final String name;
    private final String description;
    private final String defaultState;

    private final List<StatusPolicy> states;

    public IndexManagerPolicy(String name, String description, String defaultState, List<StatusPolicy> states) {
        this.name = name;
        this.description = description;
        this.defaultState = defaultState;
        this.states = states;
    }

    /**
     * @return the name of this {@link IndexManagerPolicy}
     */
    public String getName() {
        return name;
    }

    public List<StatusPolicy> getStates() {
        return states;
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        builder.field(DESCRIPTION_FIELD.getPreferredName(), description);
        builder.field(DEFAULT_STATE.getPreferredName(), defaultState);
        builder.startArray(STATES_FIELD.getPreferredName());
        for (StatusPolicy state : states) {
            state.toXContent(builder, params);
        }
        builder.endArray();
        builder.endObject();
        return builder;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, description, defaultState, states);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj.getClass() != getClass()) {
            return false;
        }
        IndexManagerPolicy other = (IndexManagerPolicy) obj;
        return Objects.equals(name, other.name) &&
                Objects.equals(description, other.description) &&
                Objects.equals(defaultState, other.defaultState) &&
                Objects.equals(states, other.states);
    }

    @Override
    public String toString() {
        return Strings.toString(this, true, true);
    }
}
